<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useAuth } from '@/composables/useAuth'
import ThemeSwitcher from '@/components/ThemeSwitcher.vue'
import UserAvatar from '@/components/common/UserAvatar.vue'
import {
  PhList,
  PhNewspaper,
  PhHouse,
  PhArticle,
  PhUser,
  PhMagnifyingGlass,
  PhPalette,
  PhX,
  PhSignIn,
  PhUserCircle,
  PhGear,
  PhSignOut,
  PhRobot,
} from '@phosphor-icons/vue'

/**
 * Props定义
 */
interface Props {
  showSearchBox?: boolean
}

const props = defineProps<Props>()

/**
 * 事件定义
 */
const emit = defineEmits<{
  toggleSearch: []
}>()

const router = useRouter()

/**
 * 用户认证
 */
const { currentUser, quickLogin, logout } = useAuth()

/**
 * 关闭移动端抽屉菜单
 */
const closeMobileDrawer = (): void => {
  const drawer = document.getElementById('mobile-drawer') as HTMLInputElement
  if (drawer) {
    drawer.checked = false
  }
}

/**
 * 切换搜索框并关闭抽屉
 */
const toggleSearchBoxAndCloseDrawer = (): void => {
  emit('toggleSearch')
  closeMobileDrawer()
}

/**
 * 处理用户登录
 */
const handleLogin = async (): Promise<void> => {
  try {
    await quickLogin()
  } catch (error) {
    console.error('登录失败:', error)
  }
}

/**
 * 处理用户登出
 */
const handleLogout = async (): Promise<void> => {
  try {
    await logout()
  } catch (error) {
    console.error('登出失败:', error)
  }
}

/**
 * 处理个人资料
 */
const handleProfile = (): void => {
  router.push('/profile')
}

/**
 * 处理设置
 */
const handleSettings = (): void => {
  router.push('/settings')
}

/**
 * 处理登录并关闭抽屉
 */
const handleLoginAndCloseDrawer = async (): Promise<void> => {
  await handleLogin()
  closeMobileDrawer()
}

/**
 * 处理登出并关闭抽屉
 */
const handleLogoutAndCloseDrawer = async (): Promise<void> => {
  await handleLogout()
  closeMobileDrawer()
}

/**
 * 处理个人资料并关闭抽屉
 */
const handleProfileAndCloseDrawer = (): void => {
  handleProfile()
  closeMobileDrawer()
}

/**
 * 处理设置并关闭抽屉
 */
const handleSettingsAndCloseDrawer = (): void => {
  handleSettings()
  closeMobileDrawer()
}

/**
 * 监听路由变化，自动关闭移动端抽屉
 */
router.afterEach(() => {
  closeMobileDrawer()
})
</script>

<template>
  <div class="drawer drawer-end">
    <input id="mobile-drawer" type="checkbox" class="drawer-toggle" />

    <!-- 导航栏 -->
    <div class="drawer-content">
      <nav
        class="navbar min-h-[3.5rem] h-14 sm:h-16 bg-base-100/95 backdrop-blur-xl border-b border-base-300/50 fixed top-0 left-0 right-0 z-50 transition-all duration-300 shadow-sm px-2 sm:px-4"
      >
        <!-- Logo（移动端和桌面端） -->
        <div class="navbar-start">
          <router-link
            to="/"
            class="btn btn-ghost h-auto min-h-0 text-base lg:text-lg font-bold hover:scale-105 transform transition-all duration-200 group px-2 md:px-4 py-1 sm:py-2"
          >
            <div
              class="w-8 h-8 md:w-10 md:h-10 bg-gradient-to-r from-primary to-secondary rounded-xl flex items-center justify-center text-primary-content text-sm md:text-lg mr-1 md:mr-3 shadow-lg group-hover:shadow-xl transition-all duration-200 flex-shrink-0"
            >
              <PhNewspaper class="w-4 h-4 md:w-6 md:h-6" />
            </div>
            <span
              class="bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent text-sm md:text-xl"
            >
              我的博客
            </span>
          </router-link>
        </div>

        <!-- 桌面端导航菜单 -->
        <div class="navbar-center hidden lg:flex">
          <ul class="menu menu-horizontal px-1 gap-1">
            <li>
              <router-link
                to="/"
                class="btn btn-ghost hover:btn-primary transition-all duration-200 gap-2"
                active-class="btn-primary"
              >
                <PhHouse :size="16" />
                首页
              </router-link>
            </li>
            <li>
              <router-link
                to="/blog"
                class="btn btn-ghost hover:btn-primary transition-all duration-200 gap-2"
                active-class="btn-primary"
              >
                <PhArticle :size="16" />
                博客
              </router-link>
            </li>
            <li>
              <router-link
                to="/about"
                class="btn btn-ghost hover:btn-primary transition-all duration-200 gap-2"
                active-class="btn-primary"
              >
                <PhUser :size="16" />
                关于
              </router-link>
            </li>
            <li>
              <router-link
                to="/ai-models"
                class="btn btn-ghost hover:btn-primary transition-all duration-200 gap-2"
                active-class="btn-primary"
              >
                <PhRobot :size="16" />
                AI 模型
              </router-link>
            </li>
          </ul>
        </div>

        <!-- 右侧操作按钮 -->
        <div class="navbar-end gap-1 md:gap-2">
          <!-- 移动端汉堡包按钮 -->
          <label
            for="mobile-drawer"
            class="btn btn-ghost btn-circle h-10 w-10 min-h-0 p-0 drawer-button lg:hidden"
          >
            <PhList :size="24" />
          </label>

          <!-- 桌面端按钮组 -->
          <div class="hidden lg:flex gap-1 md:gap-2">
            <!-- 搜索按钮 -->
            <button
              @click="emit('toggleSearch')"
              class="btn btn-ghost btn-circle h-10 w-10 md:h-12 md:w-12 min-h-0 p-0 hover:btn-primary hover:scale-110 transform transition-all duration-200 tooltip tooltip-bottom"
              :class="{ 'btn-primary scale-110': props.showSearchBox }"
              data-tip="搜索文章"
            >
              <PhMagnifyingGlass class="w-5 h-5 md:w-6 md:h-6" />
            </button>

            <!-- 主题切换器 -->
            <div class="tooltip tooltip-bottom" data-tip="切换主题">
              <ThemeSwitcher />
            </div>

            <!-- 用户头像/登录按钮 -->
            <UserAvatar
              :user="currentUser"
              @login="handleLogin"
              @logout="handleLogout"
              @profile="handleProfile"
              @settings="handleSettings"
            />
          </div>
        </div>
      </nav>
    </div>

    <!-- 移动端侧边抽屉菜单 -->
    <div class="drawer-side z-50 lg:hidden">
      <label for="mobile-drawer" class="drawer-overlay"></label>
      <div class="menu p-4 w-80 min-h-full bg-base-100 text-base-content">
        <!-- 菜单头部 -->
        <div
          class="flex items-center justify-between mb-6 pb-4 border-b border-base-300 drawer-menu-header"
        >
          <div class="flex items-center gap-3">
            <div
              class="w-10 h-10 bg-gradient-to-r from-primary to-secondary rounded-xl flex items-center justify-center text-primary-content shadow-lg"
            >
              <PhNewspaper :size="20" />
            </div>
            <div>
              <h2 class="text-lg font-bold text-base-content">我的博客</h2>
              <p class="text-xs text-base-content/60">菜单导航</p>
            </div>
          </div>
          <label for="mobile-drawer" class="btn btn-ghost btn-sm btn-circle">
            <PhX :size="20" />
          </label>
        </div>

        <!-- 导航菜单 -->
        <ul class="menu-compact space-y-2 mb-6">
          <li class="drawer-menu-item" style="--item-index: 0">
            <router-link
              to="/"
              active-class="active bg-primary text-primary-content"
              class="flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors"
            >
              <PhHouse :size="20" />
              <span class="text-base font-medium">首页</span>
            </router-link>
          </li>
          <li class="drawer-menu-item" style="--item-index: 1">
            <router-link
              to="/blog"
              active-class="active bg-primary text-primary-content"
              class="flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors"
            >
              <PhArticle :size="20" />
              <span class="text-base font-medium">博客</span>
            </router-link>
          </li>
          <li class="drawer-menu-item" style="--item-index: 2">
            <router-link
              to="/about"
              active-class="active bg-primary text-primary-content"
              class="flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors"
            >
              <PhUser :size="20" />
              <span class="text-base font-medium">关于</span>
            </router-link>
          </li>
          <li class="drawer-menu-item" style="--item-index: 3">
            <router-link
              to="/ai-models"
              active-class="active bg-primary text-primary-content"
              class="flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors"
            >
              <PhRobot :size="20" />
              <span class="text-base font-medium">AI 模型</span>
            </router-link>
          </li>
        </ul>

        <!-- 分隔线 -->
        <div class="divider my-4"></div>

        <!-- 操作按钮组 -->
        <div class="space-y-3 mb-6">
          <!-- 搜索 -->
          <button
            @click="toggleSearchBoxAndCloseDrawer"
            class="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors drawer-menu-item"
            style="--item-index: 3"
          >
            <PhMagnifyingGlass :size="20" />
            <span class="text-base font-medium">搜索文章</span>
          </button>

          <!-- 主题切换 -->
          <ThemeSwitcher>
            <template #trigger="{ open, currentTheme }">
              <button
                @click="open"
                class="w-full flex items-center justify-between p-3 rounded-lg bg-base-200 hover:bg-base-300 transition-colors drawer-menu-item cursor-pointer"
                style="--item-index: 4"
              >
                <div class="flex items-center gap-3">
                  <PhPalette :size="20" />
                  <span class="text-base font-medium">切换主题</span>
                </div>
                <!-- 显示当前主题图标 -->
                <div class="w-9 h-9 rounded-full flex items-center justify-center text-lg">
                  {{ currentTheme.icon }}
                </div>
              </button>
            </template>
          </ThemeSwitcher>
        </div>

        <!-- 分隔线 -->
        <div class="divider my-4"></div>

        <!-- 用户相关 -->
        <div class="space-y-2">
          <div v-if="!currentUser" class="drawer-menu-item" style="--item-index: 5">
            <button
              @click="handleLoginAndCloseDrawer"
              class="w-full flex items-center gap-3 p-3 rounded-lg bg-primary text-primary-content hover:bg-primary-focus transition-colors"
            >
              <PhSignIn :size="20" />
              <span class="text-base font-medium">登录</span>
            </button>
          </div>
          <div v-else class="space-y-2">
            <div
              class="flex items-center gap-3 p-3 rounded-lg bg-base-200 drawer-menu-item"
              style="--item-index: 5"
            >
              <div
                class="w-10 h-10 bg-gradient-to-r from-primary to-secondary rounded-full flex items-center justify-center text-primary-content font-bold"
              >
                {{
                  (typeof currentUser === 'string' ? currentUser : currentUser?.name || 'U').charAt(
                    0,
                  )
                }}
              </div>
              <div class="flex-1">
                <p class="text-base font-semibold">
                  {{ typeof currentUser === 'string' ? currentUser : currentUser?.name || '用户' }}
                </p>
                <p class="text-xs text-base-content/60">已登录</p>
              </div>
            </div>
            <button
              @click="handleProfileAndCloseDrawer"
              class="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors drawer-menu-item"
              style="--item-index: 6"
            >
              <PhUserCircle :size="20" />
              <span class="text-base font-medium">个人资料</span>
            </button>
            <button
              @click="handleSettingsAndCloseDrawer"
              class="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-base-200 transition-colors drawer-menu-item"
              style="--item-index: 7"
            >
              <PhGear :size="20" />
              <span class="text-base font-medium">设置</span>
            </button>
            <button
              @click="handleLogoutAndCloseDrawer"
              class="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-error hover:text-error-content transition-colors drawer-menu-item"
              style="--item-index: 8"
            >
              <PhSignOut :size="20" />
              <span class="text-base font-medium">登出</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 导航栏样式增强 */
.navbar {
  transition: all 0.3s ease;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
}

.navbar-start .btn-ghost:hover {
  background: hsl(var(--p) / 0.1);
}

/* 导航栏Logo动画 */
.navbar-start .group:hover .w-10 {
  transform: rotate(5deg) scale(1.1);
}

/* 导航链接悬停效果 */
.navbar-center .btn-ghost {
  position: relative;
  overflow: hidden;
}

.navbar-center .btn-ghost::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, hsl(var(--p) / 0.1), transparent);
  transition: left 0.5s ease;
}

.navbar-center .btn-ghost:hover::before {
  left: 100%;
}

/* 移动端菜单项悬停效果 */
.menu-compact li a {
  transition: all 0.2s ease;
}

.menu-compact li a:hover {
  transform: translateX(4px);
}

/* 抽屉菜单头部动画 */
.drawer-menu-header {
  opacity: 0;
  transform: translateX(20px);
  transition:
    opacity 0.3s ease-out,
    transform 0.3s ease-out;
}

.drawer-toggle:checked ~ .drawer-side .drawer-menu-header {
  opacity: 1;
  transform: translateX(0);
  transition-delay: 0s;
}

.drawer-toggle:not(:checked) ~ .drawer-side .drawer-menu-header {
  opacity: 0;
  transform: translateX(20px);
  transition-delay: 0s;
}

/* 抽屉菜单项动画 */
.drawer-menu-item {
  opacity: 0;
  transform: translateX(20px);
  transition:
    opacity 0.3s ease-out,
    transform 0.3s ease-out;
  transition-delay: calc(var(--item-index) * 0.05s);
}

.drawer-toggle:checked ~ .drawer-side .drawer-menu-item {
  opacity: 1;
  transform: translateX(0);
  transition-delay: calc((var(--item-index) + 1) * 0.05s);
}

/* 关闭时从上到下消失 */
.drawer-toggle:not(:checked) ~ .drawer-side .drawer-menu-item {
  opacity: 0;
  transform: translateX(20px);
  transition-delay: calc(var(--item-index) * 0.03s);
}

/* 响应式设计 */
@media (max-width: 640px) {
  .navbar {
    min-height: 3.5rem;
    height: 3.5rem;
  }

  .drawer-button.btn-circle {
    width: 2.5rem;
    height: 2.5rem;
    min-height: 2.5rem;
  }
}

@media (max-width: 1023px) {
  .navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  /* 移动端强制隐藏导航菜单 */
  .navbar-center {
    display: none !important;
  }

  /* 确保 Logo 和汉堡包显示 */
  .navbar-start,
  .navbar-end {
    display: flex !important;
  }
}

/* 确保抽屉默认隐藏 */
.drawer-toggle {
  display: none;
}

.drawer-side {
  pointer-events: none;
  visibility: hidden;
  overflow-y: auto;
  overscroll-behavior: contain;
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  display: grid;
  width: 100%;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  justify-items: end;
}

.drawer-toggle:checked ~ .drawer-side {
  pointer-events: auto;
  visibility: visible;
}

.drawer-side > * {
  grid-column-start: 1;
  grid-row-start: 1;
}

.drawer-overlay {
  position: sticky;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  cursor: pointer;
  background-color: hsl(0 0% 0% / 0.4);
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

.drawer-toggle:checked ~ .drawer-side .drawer-overlay {
  opacity: 1;
}

.drawer-side > .menu {
  transform: translateX(100%);
  transition: transform 0.3s ease-in-out;
}

.drawer-toggle:checked ~ .drawer-side > .menu {
  transform: translateX(0);
}
</style>
